/*
 * @Author: your name
 * @Date: 2019-10-21 14:27:33
 * @LastEditTime: 2019-11-06 18:07:43
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /c:\Users\DELL\Desktop\zhhu\app\controllers\User.js
 */
const jsonwebtoken = require('jsonwebtoken');
const User = require('../Models/User');
const Question = require('../Models/questions');
const {
    secret
} = require('../config');





class UserCtr {
    async find(ctx) {
        const {
            per_page = 10
        } = ctx.query;
        const page = Math.max(ctx.query.page * 1, 1) - 1;
        const perPage = Math.max(per_page * 1, 1);
        ctx.body = await User.find({
            name: new RegExp(ctx.query.q)
        }).limit(perPage).skip(perPage * page);
    }
    async findById(ctx) {
        const {
            fields = ""
        } = ctx.query; //这里是查询字符串
        const selectFields = fields.split(';').filter(f => f).map(f => ' +' + f).join('');
        const populateStr = fields.split(';').filter(f => f).map(f => {
            if (f === 'employments') {
                return "employments.company employments.job";
            }
            if (f === "educations") {
                return "educations.school educations.major ";
            }
            return f;
        }).join(' '); //这里是查询字符的解析
        console.log(populateStr)

        const user = await User.findById(ctx.params.id).select(selectFields).populate(populateStr);
        if (!user) {
            ctx.throw(404, '用户不存在')
        }
        ctx.body = user;
    }



    async create(ctx) {
        //这里是参数校验
        ctx.verifyParams({
            name: {
                type: 'string',
                required: true
            },
            password: {
                type: 'string',
                required: true
            }
        });
        const {
            name
        } = ctx.request.body;
        const repeatedUser = await User.findOne({
            name
        })
        if (repeatedUser) {
            ctx.throw(409, "用户已经存在");
        }
        const user = await new User(ctx.request.body).save();
        ctx.body = user;
    }

    //这个是判断是否本人操作
    async checkOwner(ctx, next) {
        console.log(ctx.state.user._id)
        if (ctx.params.id !== ctx.state.user._id) {
            ctx.throw(403, '没有权限修改')
        }
        await next();
    }
    async chexkUserExist(ctx, next) {
        const user = await User.findById(ctx.params.id);
        if (!user) {
            ctx.throw(404, "用户不存在哦")
        }
        await next();
    }

    async update(ctx) {
        ctx.verifyParams({
            name: {
                type: 'string',
                required: false
            },
            password: {
                type: 'string',
                required: false
            },
            avatar_url: {
                type: 'string',
                required: false
            },
            gender: {
                type: "string",
                required: false
            },
            headline: {
                type: "string",
                required: false
            },
            locations: {
                type: 'array',
                itemType: 'string',
                required: false
            },
            business: {
                type: 'string',
                required: false
            },
            employments: {
                type: 'array',
                itemType: 'object',
                required: false
            },
            educations: {
                type: 'array',
                itemType: 'object',
                required: false
            },

        })
        const user = await User.findByIdAndUpdate(ctx.params.id, ctx.request.body);
        if (!user) {
            ctx.throw(404, "该用户未找到");
        }
        ctx.body = user;
    }




    async delete(ctx) {
        const user = await User.findByIdAndRemove(ctx.params.id);
        if (!user) {
            ctx.throw(404, "该用户未找到");
        }
        ctx.status = 204;
    }


    async login(ctx) {
        ctx.verifyParams({
            name: {
                type: 'string',
                required: true
            },
            password: {
                type: 'string',
                required: true
            }
        });
        const user = await User.findOne(ctx.request.body);
        if (!user) {
            ctx.throw(401, "用户名或密码不正确");
        }
        const {
            _id,
            name
        } = user
        const token = jsonwebtoken.sign({
            _id,
            name
        }, secret, {
            expiresIn: '1d'
        });
        ctx.body = {
            token
        };
    }
    async listFollowing(ctx) { //获取关注列表
        const user = await User.findById(ctx.params.id).select("+following").populate('following'); //获取关注的用户
        if (!user) {
            ctx.throw(404)
        }
        ctx.body = user.following;
        console.log('成功获取')
    }
    async listFollowers(ctx) { //获取粉丝列表
        const users = await User.find({
            following: ctx.params.id
        })
        ctx.body = users;
    }

    async following(ctx) { //关注
        const me = await User.findById(ctx.state.user._id).select("+following");
        if (!me.following.map(id => id.toString()).includes(ctx.params.id)) {
            me.following.push(ctx.params.id);
            me.save();
        }
        ctx.status = 204;
    }

    async unfollowing(ctx) { //取消关注
        const me = await User.findById(ctx.state.user._id).select("+following");
        const index = me.following.map(id => id.toString()).indexOf(ctx.params.id);
        console.log(me.following)
        if (index > -1) {
            me.following.splice(index, 1);
            me.save();
        }
        ctx.status = 204;
    }
    //话题
    async followingTopic(ctx) { //关注话题
        const me = await User.findById(ctx.state.user._id).select("+followingTopic");
        if (!me.followingTopic.map(id => id.toString()).includes(ctx.params.id)) {
            me.followingTopic.push(ctx.params.id);
            me.save();
        }
        console.log(ctx.state)
        ctx.status = 204;
    }

    async unfollowingTopic(ctx) { //取消关注话题
        const me = await User.findById(ctx.state.user._id).select("+followingTopic");
        const index = me.followingTopic.map(id => id.toString()).indexOf(ctx.params.id);
        console.log(me.followingTopic)
        if (index > -1) {
            me.followingTopic.splice(index, 1);
            me.save();
        }
        ctx.status = 204;
    }
    async listFollowingTopic(ctx) { //获取关注列表
        const user = await User.findById(ctx.params.id).select("+followingTopic").populate('followingTopic'); //获取关注的用户
        if (!user) {
            ctx.throw(404,'用户不存在')
        }
        ctx.body = user.followingTopic;
        console.log('成功获取')
    }
    async listQuestions(ctx){
        const questions =await Question.find({questioner:ctx.params.id});
        ctx.body =questions
    }
}
module.exports = new UserCtr();